package com.party.web.biz.crowdfund;

import com.party.common.constant.Constant;
import com.party.common.utils.BigDecimalUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.Project;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.IProjectTransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 支持业务结论
 * Created by wei.li
 *
 * @date 2017/3/28 0028
 * @time 16:17
 */

@Service
public class ProjectTransferBizService {

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IProjectTransferService projectTransferService;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private IActivityService activityService;

    /**
     * 转移支持者
     * @param sourceId 资源编号
     * @param targetId 目标编号
     */
    @Transactional
    public void transferSupport(String sourceId, String targetId){
        Activity activity = activityService.get(targetId);
        Project source = projectService.get(sourceId);

        //根据目标和发起人查询
        Project target = projectService.findByTargetWithAuthor(targetId, source.getAuthorId());

        //已经报名
        if (null != target){
            if (Constant.IS_CROWFUND_ING.equals(target.getIsSuccess())){
                //验证众筹金额
                float realAmount = BigDecimalUtils.add(target.getActualAmount(), source.getActualAmount());
                realAmount = BigDecimalUtils.round(realAmount, 2);
                if ( realAmount  > target.getTargetAmount()){
                    throw new BusinessException("转移后的金额大于目标金额,不能转移");
                }
                projectTransferService.transfer(sourceId, target.getId());
            }
            else {
                throw new BusinessException("该用户在该项目已经报名,且状态不对，请核对众筹状态");
            }
        }

        //未报名
        else {
            // 自动报名
            String projectId = projectBizService.apply(activity, source);
            projectTransferService.transfer(sourceId, projectId);
        }
    }
}
